
import axios, {InternalAxiosRequestConfig} from 'axios';
import { message } from 'ant-design-vue';
import {Result} from '@/types/global.ts'
export interface AxiosConfig extends InternalAxiosRequestConfig{
    returnOriginData:boolean;
}

let axiosConfig:AxiosConfig = {} as AxiosConfig;
if (import.meta.env.VITE_API_BASE_URL) {
  axios.defaults.baseURL = import.meta.env.VITE_API_BASE_URL;
}

axios.interceptors.request.use(function (config:InternalAxiosRequestConfig|AxiosConfig) {

    axiosConfig = {...config} as AxiosConfig;

    // 在发送请求之前做些什么
    return config;
}, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
});

// add response interceptors
axios.interceptors.response.use(
  (response:any) => {
    const res = response.data;
    const whiteUrl = ['/files/downloadFile']
    // if the custom code is not 20000, it is judged as an error.
    if (!whiteUrl.includes(response.config.url)&&res.code !== 200) {
        message.error({
        content: res?.message || 'Error',
        duration: 3,
      });
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (
        [401].includes(res.code) &&
        response.config.url !== '/api/user/info'
      ) {


        sessionStorage.clear();
        localStorage.clear();
        window.location.reload();
        /* Modal.error({
          title: '是否重新登录？',
          content: '您的登录已过期, 您可以停留在此页或重新登录',
          okText: '重新登录',
          async onOk() {
            const userStore = useUserStore();

            await userStore.logout();
            window.location.reload();
          },
        }); */
      }
      return Promise.reject(new Error(res.message || 'Error'));
    }
    return axiosConfig?.returnOriginData?response: response.data as Result;
  },
  async (error) => {
    if (error.response.statusCode === 401 || error.response.data.code === 401) {
        message.error({
        content: '您的登录已过期, 请重新登录',
      });
      sessionStorage.clear();
      localStorage.clear();
      window.location.reload();

      /* Modal.error({
        title: '是否重新登录？',
        content: '您的登录已过期, 您可以停留在此页或重新登录',
        okText: '重新登录',
        async onOk() {
          const userStore = useUserStore();
          await userStore.logout();
          window.location.reload();
        },
      }); */
    } else {
        message.error({
        content: error.response.data.message || '系统错误,请联系管理员',
            duration:3
      });
    }
    return Promise.reject(error);
  }
);
